package it.free.maya.utilities;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;

/**
 * Load a properties file from a physical file
 * @author  Stefano Falconetti
 * @version $Revision: 1.1 $ $Date: 2009/07/06 05:33:55 $
 */
public class PropertiesLoader {

    /**
     * Don't use
     */
    private PropertiesLoader() {
        super();
    }
    
    /**
     * @param fileName is the name of the file to load properties from
     * @return a properties object loaded, or null if something goes wrong
     * @throws IOException
     * @throws FileNotFoundException
     * @throws IllegalArgumentException
     * @throws SecurityException 
     */
    public static final Properties loadProperties(String fileName) throws IOException, FileNotFoundException, IllegalArgumentException, SecurityException {
        
    	InputStreamReader inputStreamReader = null;
    	
        Properties properties = new Properties();
        FileInputStream fileInputStream= null;
        try{
        	fileInputStream = new FileInputStream(fileName);
        	inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
           
            properties.load(inputStreamReader);
        }finally{
                 try{
                     if(fileInputStream != null){
                        fileInputStream.close();    
                     }
                 }catch(Exception exc){
                        throw (new IOException("Unable to close file input stream"));
                 }
        }
        return properties;
    }
     
    /**
     * Retrieve from the classpath of this classloader, the path for the jndi provider properties
     * @return the complete path for the file name passed, null if missing
     */
    public static final String getConfigFileFromClasspath(String fileName){
        
        URL configurationUrl = Thread.currentThread().getContextClassLoader().getResource(fileName);
        
        String absoluteConfigurationFile = null;
        if(configurationUrl == null){
           return absoluteConfigurationFile;
        }
        absoluteConfigurationFile = configurationUrl.getFile();
        return absoluteConfigurationFile;
    }
}
